package liurong.driver.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
	private static ReentrantLock lock = new ReentrantLock();
	private static Condition condition1;
	private static Condition condition2;

	public static void main(String[] args) {
		condition1 = lock.newCondition();
		condition2 = lock.newCondition();

		Thread thread1 = new Thread(new Runnable() {

			public void run() {
				while (true) {
					if (lock.tryLock()) {
						try {
							condition1.await();
							System.out.println("thread1");
							condition2.signal();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} finally {
							lock.unlock();
						}
					}
				}
			}
		});
		Thread thread2 = new Thread(new Runnable() {

			public void run() {
				while (true) {
					if (lock.tryLock()) {
						try {
							TimeUnit.SECONDS.sleep(1);
							condition1.signal();
							System.out.println("thread2");
							condition2.await();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} finally {
							lock.lock();
						}
					}
				}
			}
		});
		thread1.setDaemon(false);
		thread2.setDaemon(false);
		thread1.start();
		thread2.start();
	}
}
